/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-09-02 22:47:16
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-09-03 22:05:40
 * @FilePath: /metaverse-manage/app/controller/Model.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Controller } from 'egg';
import { response } from '../utils/common';
import path from 'node:path';
import fs from 'node:fs';
import zlib from 'zlib';


export default class FileController extends Controller {
  async upload() {
    const { ctx } = this;

    const file = ctx.request.files[0];
    if (!file) {
      ctx.body = response(null, 412);
      return;
    }
    try {
      const ext = path.extname(file.filename).toLowerCase();
      const timestamp = Date.now(); // 获取当前时间戳
      // 定义保存的文件路径
      const savePath = path.join(this.config.baseDir, '/app/public', `${timestamp}${ext}`);
      // 创建文件流并写入
      const reader = fs.createReadStream(file.filepath);
      const stream = fs.createWriteStream(savePath);
      reader.pipe(stream);
      ctx.body = response(`public/${timestamp}${ext}`);
    } catch (error) {
      ctx.body = response(error, 500);
    } finally {
      // 清理临时文件
      await ctx.cleanupRequestFiles();
    }
  }


  down() {
    const { ctx } = this;
    const filePath = path.join(__dirname, 'your-file.txt');
    ctx.set('Content-Encoding', 'gzip');
    ctx.set('Content-Type', 'application/octet-stream');
    ctx.set('Content-Disposition', 'attachment; filename=your-file.txt.gz');

    const readStream = fs.createReadStream(filePath);
    const gzipStream = zlib.createGzip();

    ctx.body = readStream.pipe(gzipStream);
  }
}
